using System;
using System.Text;
using System.Net.Sockets;

using Domain;

namespace Client
{
    public class Client
    {
        private Socket socket;

        public Client()
        {
            // Constructor
        }

        public bool isConnected()
        {
            if (socket == null) return false;
            return socket.Connected;
        }

        public bool Connect(string ip, int port)
        {
            try
            {
                // Initiate socket
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // Connect to server
                socket.Connect(ip, port);
                return true;
            }

            catch (SocketException se)
            {
                if (socket != null)
                {
                    socket.Close();
                }

                Console.WriteLine(se);

                return false;
            }
        }

        public bool Disconnect()
        {
            try
            {
                socket.Close();

                return true;
            }

            catch (SocketException se)
            {
                Console.WriteLine(se);

                return false;
            }
        }

        public bool Send(string message)
        {
            try
            {
                // Convert to bytes
                byte[] data = Encoding.ASCII.GetBytes(message);

                // Send data over socket
                socket.Send(data);

                return true;
            }

            catch (SocketException se)
            {
                Console.WriteLine(se);

                return false;
            }
        }

        public int receive(byte[] buffer)
        {
            return socket.Receive(buffer);
        }

        // Call backs
        public void WaitForData()
        {

        }

        public void OnDataReceived(IAsyncResult asyn)
        {

        }
    }
}
